<!-- 新增巡检计划页面 -->
<template>
  <div v-if="!isMain && isAdd" class="add-inspect-plan">
    <div class="add-inspect-plan-wrapper">
      <div class="add-inspect-plan-content">
        <px-button style="margin-top: 16px; margin-bottom: 16px" type="primary" icon="ArrowLeft" @click="backMainPage(true)">返回</px-button>
        <px-scrollbar class="add-equip-body">
          <px-form
            ref="formRef"
            :inline="false"
            if
            :model="formValue"
            :rules="rules"
            label-position="right"
            label-width="150px"
            :validate-on-rule-change="false"
          >
            <div>
              <EditDropDown dropdownTitle="基本信息" style="margin-top: 0">
                <template v-slot:content>
                  <div class="block w-[100%]">
                    <px-row :gutter="22">
                      <px-col :span="8">
                        <px-form-item label="巡检计划编号" prop="planCode">
                          <px-input v-model="formValue.planCode" disabled />
                        </px-form-item>
                      </px-col>
                      <px-col :span="8">
                        <px-form-item label="巡检计划名称" prop="planName">
                          <px-input
                            v-model="formValue.planName"
                            placeholder="请输入巡检计划名称"
                            maxlength="50"
                            clearable
                            @blur="formValue.planName = $event.target.value.trim()"
                          />
                        </px-form-item>
                      </px-col>
                      <px-col :span="8">
                        <!-- 科室 -->
                        <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
                      </px-col>
                      <px-col :span="8">
                        <px-form-item label="巡检类型" prop="inspectType">
                          <px-radio-group v-model="formValue.inspectType" :disabled="maintainDisabled">
                            <px-radio :label="1">日常巡检</px-radio>
                            <px-radio :label="2">专项巡检</px-radio>
                          </px-radio-group>
                        </px-form-item>
                      </px-col>
                      <px-col :span="8">
                        <px-form-item label="巡检组" prop="groupCode">
                          <px-select
                            v-model="formValue.groupCode"
                            :disabled="!formValue.className"
                            clearable
                            filterable
                            placeholder="请先选择科室"
                            style="width: 100%"
                            @focus="changeCheckGroupCode"
                          >
                            <px-option v-for="item in checkGroupList" :key="item.id" :label="item.name" :value="item.code" />
                          </px-select>
                        </px-form-item>
                      </px-col>
                      <px-col :span="24">
                        <px-form-item label="说明" prop="description">
                          <px-input
                            v-model="formValue.description"
                            placeholder="请输入巡检计划说明信息"
                            maxlength="1000"
                            show-word-limit
                            clearable
                            type="textarea"
                          />
                        </px-form-item>
                      </px-col>
                    </px-row>
                  </div>
                </template>
              </EditDropDown>
            </div>
            <div>
              <EditDropDown dropdownTitle="执行周期">
                <template v-slot:content>
                  <ExecutionCycle :form-value="formValue" @change="handelExecutionCycleChange" />
                </template>
              </EditDropDown>
            </div>
            <div>
              <EditDropDown dropdownTitle="巡检规则">
                <template v-slot:content>
                  <div class="w-[100%]">
                    <px-row :gutter="22">
                      <px-col :span="24">
                        <px-button type="primary" ghost class="mb-[10px]" @click="handleSelectEquip">选择巡检规则</px-button>
                        <InspectRulesTable
                          :table-data="tableEqiupSelected"
                          :tableColumns="tableEqiupColums"
                          :total="0"
                          :hasDrag="true"
                          class="w-[100%]"
                          @on-drag="tableEqiupDrag"
                          @del="deleteEquipSelected"
                        />
                      </px-col>
                    </px-row>
                  </div>
                </template>
              </EditDropDown>
            </div>
          </px-form>
        </px-scrollbar>
      </div>
      <div class="info-form-btns">
        <px-button @click="backMainPage(true)">取消</px-button>
        <px-button v-if="!planNo || formValue.planStatus == 1" type="primary" ghost @click="handleDraft(formRef)">保存草稿</px-button>

        <px-button type="primary" @click="handleSubmit(formRef)">发布巡检计划</px-button>
      </div>
    </div>
    <SelectInspectEquip
      v-model:is-view="isAddEquip"
      :inspectType="formValue.inspectType"
      :className="formValue.className"
      :typeCodeList="typeCodeList"
      @select-items="selectEquipItems"
    />
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { cloneDeep } from "@pureadmin/utils";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { ExecutionCycle } from "../../components/index";
import SelectInspectEquip from "./SelectInspectEquip.vue";
import { getRuleCode, inspectPlanAdd, inspectPlanAddDraft, inspectPlanView } from "@/api/equip/inspect";
import { PxMessageBox } from "px-ui";
import { TableItem } from "../../types";
import InspectRulesTable from "./InspectRulesTable.vue";
import { getOpsGroupList } from "@/api/equip/maintain";

const tableEqiupColums = ref<TableItem[]>([
  { prop: "drag", minWidth: "60" },
  { prop: "ruleCode", label: "巡检规则编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "ruleName", label: "巡检规则名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "inspectTypeDesc", label: "巡检类型", minWidth: "160", showOverflowTooltip: true },
  { prop: "classNameDesc", label: "科室", minWidth: "160", showOverflowTooltip: true },
  { prop: "inspectAreaDesc", label: "巡检区域", minWidth: "160", showOverflowTooltip: true },
  { prop: "operate", minWidth: "55", label: "操作", showOverflowTooltip: true, fixed: "right" }
]);
const isMain = defineModel("isMain");
const isAdd = defineModel("isAdd");
const planNo = defineModel("planNo");
const isCopy = defineModel("isCopy");

//form表单相关
const formRef = ref();
let formDataTmpl = {
  planCode: "", //计划编号
  planName: "", //计划名称
  className: "",
  groupCode: "",
  planStatus: 0,
  execType: "1", //执行方式 1-固定时间,2-周期时间
  inspectType: 1, //巡检类型
  execStartDate: "", //执行开始日期
  execEndDate: "", //执行结束日期
  execDuration: 0, //执行时长
  execDurationUnit: "HOUR", //执行时长单位
  extendDuration: 0, //宽泛期
  extendDurationUnit: "HOUR", //宽泛期单位
  cyclePerNum: 0, //排查周期
  cyclePerUnit: "DAY", //	排查周期单位
  cycleValue: "", //排查周期值
  cycleTime: "", //周期时间
  taskCreateTime: "", //	任务生成并提醒时间
  description: "",
  ruleCodeList: [] //回显数据保存-规则编码列表
};
const formValue = ref(cloneDeep(formDataTmpl));
const maintainDisabled = ref(false); //单选框是否禁用
const isBack = ref(true);
const validateRulesTable = (rule: any, value: any, callback: any) => {
  if (!tableData.value || tableData.value?.length === 0) {
    callback(new Error("请选择巡检规则"));
  } else {
    callback();
  }
};
const rules = reactive({
  planCode: [{ required: true, trigger: "blur" }],
  planName: [
    {
      required: true,
      message: "请输入巡检计划名称",
      trigger: "blur"
    }
  ],
  groupCode: [
    {
      required: true,
      message: "请选择巡检组",
      trigger: "change"
    }
  ],
  tableData: [
    //需要自定义规则
    {
      required: true,
      validator: validateRulesTable,
      trigger: "blur"
    }
  ],
  execType: [
    //需要自定义规则
    {
      required: true,
      message: "请选择执行方式",
      trigger: "change"
    }
  ],
  execStartDate: [
    //需要自定义规则
    {
      required: true,
      message: "请选择执行方式",
      trigger: "change"
    }
  ],
  execEndDate: [
    //需要自定义规则
    {
      required: true,
      message: "请选择执行方式",
      trigger: "change"
    }
  ],
  execDuration: [
    {
      required: true,
      message: "请选择执行时长",
      trigger: "blur"
    }
  ],
  taskCreateTime: [
    {
      required: true,
      message: "请选择任务生成并提醒时间",
      trigger: "change"
    }
  ]
});
const checkGroupList = ref([]); //任务分配下拉
const isAddEquip = ref(false);
// 巡检规则table
const tableData = ref([]);
//选择设备table
const tableEqiupSelected = ref([]);
//查询条件
watch(
  () => isAdd.value,
  async () => {
    // formValue.value.inspectType = 1;
    if (isAdd.value) {
      setTimeout(() => {
        formRef?.value.clearValidate();
      }, 0);
      if (!planNo.value) {
        //新增
        const planCode = await getRuleCode();
        formValue.value.planCode = planCode;
      } else {
        // 详情
        let detail: { [key in string] } = await inspectPlanView({ id: planNo.value });
        detail.execType = String(detail.execType);
        const { checkRuleList, ruleDTOList } = detail as any;
        // tableData.value = checkRuleList?.length > 0 ? checkRuleList : [];
        tableEqiupSelected.value = ruleDTOList?.length > 0 ? ruleDTOList : [];
        formValue.value = detail;
        if (isCopy.value) {
          // 复制
          const planCode = await getRuleCode();
          formValue.value.planCode = planCode;
          formValue.value.planName = "";
          formValue.value.execStartDate = "";
          formValue.value.execEndDate = "";
          formValue.value.planStatus = 1;
          delete formValue.value.id;
        }
        delete formValue.value.ruleDTOList;
      }
    } else {
      planNo.value = "";
    }
  }
);
watch(tableData, () => {
  if (tableData.value.length > 0) {
    formRef?.value.clearValidate("tableData");
  }
});
//返回主菜单
const backMainPage = (isBack?: boolean) => {
  if (isBack) {
    PxMessageBox.confirm("内容未保存，确认退出此巡检计划吗", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        isAdd.value = false;
        isMain.value = true;
        resetForm();
        planNo.value = "";
        isCopy.value = false;
      })
      .catch(() => {});
  } else {
    isAdd.value = false;
    isMain.value = true;
    resetForm();
    planNo.value = "";
    isCopy.value = false;
  }
};
//任务分配值改变出发的事件
const changeCheckGroupCode = async () => {
  const data: any = await getOpsGroupList({ className: formValue.value.className });
  checkGroupList.value = data;
};
//reset表单
const resetForm = () => {
  if (!formRef?.value) return;
  formRef.value.resetFields();
  formValue.value = cloneDeep(formDataTmpl);
  tableData.value = [];
  tableEqiupSelected.value = [];
};
//表单提交
async function handleSubmit(formEl) {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      transformFormToSave();
      PxMessageBox.confirm("确定发布巡检计划吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          await inspectPlanAdd(formValue.value);
          backMainPage();
        })
        .catch(() => {});
    } else {
    }
  });
}
//保存草稿
async function handleDraft(formEl) {
  if (!formEl) return;
  isBack.value = false;
  transformFormToSave();
  formValue.value.planStatus = 1; //草稿状态
  await inspectPlanAddDraft(formValue.value);
  backMainPage();
}
//数据回显
function transformFormToSave() {
  formValue.value.ruleCodeList = extractValuesByKey(tableEqiupSelected.value, "ruleCode");
}
//将对象转化为数组--取表格的数据
function extractValuesByKey(array, key) {
  const result = [];
  for (const obj of array) {
    if (obj.hasOwnProperty(key)) {
      result.push(obj[key]);
    }
  }
  return result;
}
//选择巡检设备内函数
function tableEqiupDrag(evt) {
  const oldItem = tableEqiupSelected.value[evt.oldIndex];
  tableEqiupSelected.value.splice(evt.oldIndex, 1);
  tableEqiupSelected.value.splice(evt.newIndex, 0, oldItem);
}

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  // systemCodes.value = [];
  if (!isOnlyClass) {
    tableEqiupSelected.value = [];
    formRef.value?.resetFields(["categoryId", "typeId", "modelId", "eqpId", "eqpName", "groupCode"]);
  }
};
// //科室changeCheckGroup
// function changeCheckGroup(val) {
//   formValue.value.className = val;
//   formValue.value.groupCode = "";
//   tableEqiupSelected.value = [];
// }
//选择规则--弹窗出现
function handleSelectEquip() {
  const { className, groupCode } = formValue.value;
  if (className && groupCode) {
    isAddEquip.value = true;
  } else {
    formRef?.value.validateField("className");
    formRef?.value.validateField("groupCode");
  }
}
//巡检规则--巡检规则
const typeCodeList = computed(() => {
  return tableData.value.reduce((pre, cur) => {
    return [...pre, cur.eqpTypeCode];
  }, []);
});
//设备选择回显
function selectEquipItems(val) {
  tableEqiupSelected.value = mergeAndDeduplicate(tableEqiupSelected.value, val, "id");
}
function mergeAndDeduplicate(arr1, arr2, key) {
  const map = new Map();
  // 合并两个数组
  const combinedArray = [...arr1, ...arr2];
  // 遍历合并后的数组，并根据 key 去重
  combinedArray.forEach(item => {
    map.set(item[key], item);
  });
  // 将 Map 转换回数组
  return Array.from(map.values());
}
function deleteEquipSelected(row) {
  tableEqiupSelected.value = tableEqiupSelected.value.filter(item => item["id"] !== row["id"]);
}
//执行周期组件内函数
const handelExecutionCycleChange = val => {
  Object.assign(formValue.value, val);
};
onMounted(async () => {
  changeCheckGroupCode();
});
</script>
<style lang="scss" scoped>
.add-inspect-plan {
  display: flex;
  width: 100%;
  height: calc(100vh - 195px);
  padding: 0 24px 24px;
  overflow-x: auto;
  background-color: #fff;
  border-radius: 8px;

  .add-equip-body {
    height: calc(100vh - 278px);
  }

  ._form-rules {
    :deep(.px-form-item__content) {
      flex-direction: column;
      align-items: flex-start;
    }
  }

  .add-inspect-plan-content {
    :deep(.px-form) {
      width: 100%;

      .px-form-item {
        width: 100%;
        margin-right: 0;

        .px-input {
          width: 100%;
        }

        .px-select {
          width: 100%;
        }

        .px-select-v2 {
          width: 100%;
        }

        .px-input-number {
          width: 100%;

          .px-input__inner {
            text-align: left;
          }
        }

        &.is-error {
          .px-input-number {
            .px-input__wrapper {
              border: 1px solid var(--px-color-danger);
              box-shadow: none;
            }
          }
        }
      }
    }

    .equip-table {
      --px-table-border-color: #dfdfdf;

      margin-bottom: 18px;
      font-size: 14px;

      :deep(.px-table__header) {
        thead {
          tr {
            background-color: #e7eefb !important;

            th {
              font-size: 14px;
              font-weight: bold;
              color: #000;
              background-color: #e7eefb !important;
            }
          }
        }
      }

      :deep(.px-input-number) {
        width: 100%;
      }
    }
  }

  &-wrapper {
    width: 100%;
  }

  .info-form-btns {
    position: absolute;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 68px;
    padding-right: 24px;
    background: #fff;
    box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
  }
}
</style>
